Home:ALL Converter>Ansible playbook - syntax in set_fact with variables and ip filter - centos7

Ansible playbook - syntax in set_fact with variables and ip filter - centos7

Ask Time:2018-03-27T10:06:10         Author:Louis.C

Json Formatter

In centos7, I am trying to define a remote host, where IP is the back-end or front-end IP Then I ordered the IPADDR filter and there were some obstacles.

For example,

# {{ ansible_all_ipv4.addresses | ipaddr('192.168.0.0/22') }}
['192.168.1.2', '192.168.2.2']

# {{ ansible_all_ipv4.addresses | ipaddr('192.168.1.0/24') }}
['192.168.1.2']

As my case, since in VM have 2 different IPs like 192.168.56.101 and 172.16.1.10, i want to pre-define the network and prefix by variables to get the 192.168.56.101. Then i set:

[defaults/main.yml]
backend:
 network: 192.168.56.0
 prefix: 24

[tasks/main.yml]
- debug: var="{{item}}"
  with_items:
   - "ansible_all_ipv4_addresses|ipaddr('''{{backend.network}}/{{backend.prefix}}''')"

result: 
TASK [test : debug] ************************************************************
ok: [localhost] => (item=ansible_all_ipv4_addresses|ipaddr('''192.168.56.0/24''')) => {
    "ansible_all_ipv4_addresses|ipaddr('''192.168.56.0/24''')": [
        "192.168.56.101"    <------ THAT IS WHAT I WANT
    ], 
    "changed": false, 
    "item": "ansible_all_ipv4_addresses|ipaddr('''192.168.56.0/24''')"

Then I try to set fact and export the result, its not my want.

- name: define backend ip
  set_fact:  backendIP="{{ item }}"
  with_items:
   - "ansible_all_ipv4_addresses|ipaddr('''{{network}}/{{prefix}}''')"

- debug: var=backendIP

result:
TASK [test : define backend ip] ***********************************************************
ok: [localhost] => (item=ansible_all_ipv4_addresses|ipaddr('''192.168.56.0/24'''))

TASK [test : debug] ************************************************************
ok: [localhost] => {
    "backendIP": "ansible_all_ipv4_addresses|ipaddr('''192.168.56.0/24''')"

So how can I set the variable through this situation

Author:Louis.C,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/49503330/ansible-playbook-syntax-in-set-fact-with-variables-and-ip-filter-centos7
yy